//
//  HomeFeedViewController.m
//  XiaoHongShu
//
//  Created by Jason on 2022/6/17.
//

#import "HomeFeedViewController.h"
#import "HomeFeedCell.h"
#import "ItemFrame.h"
#import "MainDataModel.h"
#import "DataModel.h"
#import "WaterFallFlowLayout.h"
#import "DescNormalViewController.h"
#import "DescVideoViewController.h"


#define itemMargin 5
@interface HomeFeedViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>
@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) WaterFallFlowLayout *layout;

@property (nonatomic, strong) NSMutableArray<ItemFrame *> *dataArr;

// 记录scrollView.contentInset.top
@property (nonatomic, assign)CGFloat marginTop;

//上拉的页数
@property (nonatomic, assign) NSInteger pageNum;

@end

static Boolean autoRefresh = true;

@implementation HomeFeedViewController

-(NSMutableArray<ItemFrame *> *)dataArr {
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return  _dataArr;
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    NSLog(@"---viewWillAppear---");
}
- (void)viewDidLoad {
    [super viewDidLoad];
//    self.view.backgroundColor = self.bgColor;
    
    NSLog(@"tyep = %@", self.type);
    [self.view addSubview:self.collectionView];
    
    //下拉刷新
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.pageNum = 1;
        [self loadRequest:MJRefreshTypePullDown pageNum:self.pageNum];
    }];
//    //开始下拉刷新
//    [self.collectionView.mj_header beginRefreshing];
    
    //上拉加载
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.pageNum++;
        [self loadRequest:MJRefreshTypePullUp pageNum:self.pageNum];
    }];
   // [footer setTitle:@"我也是有底线的" forState:MJRefreshStateNoMoreData];
    self.collectionView.mj_footer = footer;    
}

#pragma mark - 懒加载WaterFallFlowLayout
-(WaterFallFlowLayout *)layout {
    if (!_layout) {
        // item 布局
        _layout = [[WaterFallFlowLayout alloc]init];
        __weak typeof(self) weakSelf = self;
        _layout.itemHeightBlock = ^CGFloat(NSIndexPath * _Nonnull indexPath) {
            ItemFrame *itemFrame = weakSelf.dataArr[indexPath.item];
            return itemFrame.itemHeight;
        };
    }
    return _layout;
}

#pragma mark - 懒加载collectionView
-(UICollectionView *)collectionView {
    if (!_collectionView) {
        
       // UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        //两行item之间的最小间距
       // layout.minimumLineSpacing = itemMargin;
        //一行中两个item之间的最小间距
       // layout.minimumInteritemSpacing = itemMargin;
       // layout.itemSize = CGSizeMake(170, 270);
      //  layout.sectionInset = UIEdgeInsetsMake(5, itemMargin, 0, itemMargin);
      //  layout.collectionViewContentSize = CGSizeMake((kSPScreenWidth - itemMargin * 3) / 2, <#CGFloat height#>)
        //设置colllectionView的滚动方向
     //   layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, kSPScreenWidth, kSPScreenHeight -40 - [UIDevice vg_navigationFullHeight] - [UIDevice vg_tabBarFullHeight]) collectionViewLayout:self.layout];
        
        NSLog(@"self.view.frame.size.height: %f", self.view.frame.size.height);
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        if (@available(iOS 13.0, *)) {
            _collectionView.backgroundColor = [UIColor systemGroupedBackgroundColor];
        } else {
            _collectionView.backgroundColor = [UIColor groupTableViewBackgroundColor];
        }
        //_collectionView.alwaysBounceVertical = YES;
        //注册cell
        [_collectionView registerClass:[HomeFeedCell class] forCellWithReuseIdentifier:@"item_cell"];
        
        NSLog(@"***frame = %@",NSStringFromCGRect(self.view.frame));
    }
    return _collectionView;
}

#pragma mark - numberOfItemsInSection
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArr.count;
}

#pragma mark - cellForItemAtIndexPath
-(__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    HomeFeedCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"item_cell" forIndexPath:indexPath];
//    if (!cell) {
//        cell = [[HomeFeedCell alloc]init];
//    }
    if (@available(iOS 13.0, *)) {
        cell.backgroundColor = [UIColor secondarySystemGroupedBackgroundColor];
    } else {
        cell.backgroundColor = kWhiteColor;
    }
    cell.layer.cornerRadius = 5;
    cell.layer.masksToBounds = YES;
    cell.itemFrame = self.dataArr[indexPath.item];
    
    return cell;
}


//-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
//    ItemFrame *itemFrame = self.dataArr[indexPath.row];
//    return CGSizeMake((kSPScreenWidth - itemMargin * 3) / 2 , itemFrame.itemHeight);
//}



-(void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    
}

-(void)setIsCurrentLoad:(BOOL)isCurrentLoad {
    _isCurrentLoad = isCurrentLoad;
    if (isCurrentLoad) {
//        //开始下拉刷新
        [self.collectionView.mj_header beginRefreshing];
    }
}


#pragma mark - 网络请求 loadRequest
- (void)loadRequest:(MJRefreshType )refreshType pageNum:(NSInteger)pageNum {
    if (!_isCurrentLoad) {
        return;
    }

    NSDictionary *pageDict = @{
        @"current": @(pageNum),
        @"size": @(15)
    };
    NSDictionary *paramDict = @{
        // @"idList": @[@6780, @6790, @5984, @5985, @5985, @5986, @5987],
        @"page": pageDict,
        @"categoryId": @(self.type.integerValue)
       // @"type": @"video"
    };
    NSLog(@"开始请求 参数为= %@", paramDict);
    [[HttpRequest shareInstance] post:kNotesList parameters:paramDict success:^(NSURLSessionDataTask * _Nonnull task, HttpResponseModel * _Nullable responseModel) {
        NSLog(@"responseModel = %@", responseModel);
        if (responseModel.code.integerValue == 0) {
            NSLog(@"笔记列表请求成功");
            NSDictionary *dict = responseModel.data;
            DataModel *dataModel = [DataModel yy_modelWithDictionary:dict];
            //获取 MainDataModel
            NSArray<BaseModel *> *arr = [MainDataModel arrayFromJSONArray:dataModel.records];
            if (refreshType == MJRefreshTypePullDown) {  //下拉刷新
                [self.dataArr removeAllObjects];
                if (arr != nil && arr.count > 0) {
                    [self dataArrWithItemFrameRequestGetArr:arr];
                    self.collectionView.mj_footer.hidden = NO;
                    [self.collectionView.mj_footer endRefreshing];
                } else {
                    [super showNoDataImage];
                    NSLog(@"暂无数据。。。");
                    self.collectionView.mj_footer.hidden = YES;
                }
                [self.collectionView.mj_header endRefreshing];
            }
            if (refreshType == MJRefreshTypePullUp) {  //上拉加载
                if (arr != nil && arr.count > 0) {
                    [self dataArrWithItemFrameRequestGetArr:arr];
                    [self.collectionView.mj_footer endRefreshing];
                } else {
                    [self.collectionView.mj_footer endRefreshingWithNoMoreData];
                }
            }
            
            // [self.collectionView layoutIfNeeded];
            //刷新 collectionView
            [self.collectionView reloadData];
//            NSLog(@"dataArr = %@",self.dataArr);
            NSLog(@"category = %@ count = %ld",self.type, self.dataArr.count);
            
        } else {
            [PRTools showProgressHUDWithError:responseModel.message afterDelay:1];
            [self.collectionView.mj_header endRefreshing];
            [self.collectionView.mj_footer endRefreshing];
        }
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            [PRTools showProgressHUDWithError:@"加载失败..." afterDelay:1];
            [self.collectionView.mj_header endRefreshing];
            [self.collectionView.mj_footer endRefreshing];
        }];
}

#pragma mark - 封装请求成功获取的模型数组
- (void)dataArrWithItemFrameRequestGetArr:(NSArray *)arr {
    for (MainDataModel *mainModel in arr) {
        ItemFrame *itemFrame = [[ItemFrame alloc]init];
        [itemFrame setMainDataModel: mainModel];
        [self.dataArr addObject:itemFrame];
    }
}

#pragma mark - UICollectionViewDelegate
//-(void)collectionView:(UICollectionView *)collectionView fectItemAtIndexPath:(NSIndexPath *)indexPath {
//    //获取 MainDemodel 数据
//    ItemFrame *itemframe = self.dataArr[indexPath.item];
//    MainDataModel *mainModel = itemframe.mainDataModel;
//    NSLog(@"mainModel = %@",mainModel);
//    if ([mainModel.type isEqualToString:@"normal"]) {
//        DescNormalViewController *descNormalVC = [[DescNormalViewController alloc]init];
//        [self.navigationController pushViewController:descNormalVC animated:NO];
//    } else {
//        DescVideoViewController *descVideoVC = [[DescVideoViewController alloc]init];
//        descVideoVC.mainModel = mainModel;
//        [self.navigationController pushViewController:descVideoVC animated:NO];
//    }
//}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    //获取 MainDemodel 数据
    ItemFrame *itemframe = self.dataArr[indexPath.item];
    MainDataModel *mainModel = itemframe.mainDataModel;
    NSLog(@"mainModel = %@",mainModel);
    if ([mainModel.type isEqualToString:@"normal"]) {
        DescNormalViewController *descNormalVC = [[DescNormalViewController alloc]init];
        [self.navigationController pushViewController:descNormalVC animated:NO];
    } else {
        DescVideoViewController *descVideoVC = [[DescVideoViewController alloc]init];
        descVideoVC.mainModel = mainModel;
        [self.navigationController pushViewController:descVideoVC animated:NO];
    }
}





#pragma mark - UIScrollViewDelegate

//- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
//    NSLog(@"--scrollViewDidScroll--");
//    NSLog(@"scrollView.contentOffset.y = %f", scrollView.contentOffset.y);
//    if (self.marginTop != scrollView.contentInset.top) {
//        self.marginTop = scrollView.contentInset.top;
//    }
//
//    CGFloat offsetY = scrollView.contentOffset.y;  //-91 = 44 + 47
//    CGFloat newoffsetY = offsetY + self.marginTop;
//
//    // 临界值150，向上拖动时变透明
//    if (newoffsetY >= 0 && newoffsetY <= 150) {
//       // [self.navigationController.navigationBar jp_setNavigationBarBackgroundAlpha:1- newoffsetY/150];
//        self.navigationController.navigationBarHidden = YES;
//    }else if (newoffsetY > 150){
//       // [self.navigationController.navigationBar jp_setNavigationBarBackgroundAlpha:0];
//        self.navigationController.navigationBarHidden = YES;
//    }else{
//       // [self.navigationController.navigationBar jp_setNavigationBarBackgroundAlpha:1];
//        self.navigationController.navigationBarHidden = NO;
//    }
//}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
